import { _decorator, Component, input, Input, instantiate, Node, Prefab, RigidBody, Vec3, type EventTouch } from 'cc'
const { ccclass, property } = _decorator

@ccclass('attackCtrl')
export class NewComponent extends Component {
  @property(Prefab)
  public bulletPrefab: Prefab = null

  @property(Node)
  public bulletBox: Node = null

  @property
  public bulletSpeed = 1

  @property
  public fireRate = 0.3

  private fireTimer = 0

  private isTouching = false

  start() {
    input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
    input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
  }

  update(deltaTime: number) {
    if (this.isTouching) {
      this.fireTimer += deltaTime
      if (this.fireTimer > this.fireRate) {
        this.fire()
        this.fireTimer = 0
      }
    }
  }

  onTouchStart(event: EventTouch) {
    this.isTouching = true
  }

  onTouchEnd(event: EventTouch) {
    // console.log('onTouchEnd')
    this.isTouching = false
  }

  fire() {
    // 生成子弹实例
    const bullet = instantiate(this.bulletPrefab)

    // 添加实例到父组件
    bullet.setParent(this.bulletBox)

    // 设置子弹初始位置
    // bullet.setPosition(0, 0, 0)
    bullet.setWorldPosition(this.node.position)

    const rgd = bullet.getComponent(RigidBody)
    rgd.setLinearVelocity(new Vec3(0, 0, -this.bulletSpeed))
  }
}
